package com.springboot.common.handler;


import com.springboot.common.base.ResponseResult;
import com.springboot.common.constant.ErrorCode;
import com.springboot.common.helper.RequestHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice(annotations = RestController.class)
@ResponseBody
public class ResponseExceptionHandler {

    private static Logger logger = LoggerFactory.getLogger(RequestLogHandler.class);



    @ExceptionHandler(Exception.class)
    public ResponseResult<Object> exception(Exception e) {
        HttpServletRequest request = RequestHelper.getRequest();
        System.out.println(request);
        String errorCode = ErrorCode.ERROR.getCode();
        String errorMsg = RequestHelper.getRequestURI() + ErrorCode.ERROR.getMessage();

        ResponseResult<Object> responseResult = new ResponseResult<Object>(errorCode, errorMsg);
        String requestId = (String) request.getAttribute(RequestLogHandler.REQUEST_ID);
        responseResult.setRequestId(requestId);
        StringBuffer info = (StringBuffer) request.getAttribute(RequestLogHandler.REQUEST_LOG_INFO);
        // 处理完请求，返回内容
        info.append("[==响应结果=======]>:");

        info.append("{errorCode:").append(errorCode).append(",errorMsg:").append(errorMsg);

        //日志输出结束
        info.append("\n");

        logger.info(info.toString());

        logger.error("请求异常==>: " + e);

        return responseResult;
    }
}
